package com.eelye.util.spring;

import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ResponseHandler implements HandlerMethodReturnValueHandler, AsyncHandlerMethodReturnValueHandler {

    @Override
    public boolean isAsyncReturnValue(Object o, MethodParameter methodParameter) {
        return supportsReturnType(methodParameter);
    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return methodParameter.getAnnotatedElement().getAnnotation(ObjectResponse.class) != null;
    }

    @Override
    public void handleReturnValue(Object data, MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest) throws Exception {
        modelAndViewContainer.setRequestHandled(true);

        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        if (null == response) {
            return;
        }
        OutputObjectResponse(response, data);
    }

    public static void OutputObjectResponse(HttpServletResponse response, Object data) throws IOException {
        //虽然Deprecated了，但为了兼容性，还是这样用
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        Map<String, Object> responseContent = new HashMap<>();
        responseContent.put("errCode", 0);
        responseContent.put("errMsg", "OK");
        responseContent.put("data", data);

        response.getWriter().write(JSON.toJSONString(responseContent));
    }
}
